﻿using System;
using System.Reflection.Emit;
using Sigil.Impl;

namespace Sigil
{
	public partial class Emit<DelegateType>
	{
		/// <summary>
		/// Converts a TypedReference on the stack into a reference to the contained Object, given the type contained in the TypedReference.
		///
		/// __makeref(Int32) on the stack would become an Int32&amp;, for example.
		/// </summary>
		public Emit<DelegateType> ReferenceAnyValue<Type>()
		{
			return ReferenceAnyValue(typeof(Type));
		}

		/// <summary>
		/// Converts a TypedReference on the stack into a reference to the contained Object, given the type contained in the TypedReference.
		///
		/// __makeref(Int32) on the stack would become an Int32&amp;, for example.
		/// </summary>
		public Emit<DelegateType> ReferenceAnyValue(Type type)
		{
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}

			var transitions =
					new[]
                {
                    new StackTransition(new[] { typeof(TypedReference) }, new[] { type.MakeByRefType() })
                };

			UpdateState(OpCodes.Refanyval, type, Wrap(transitions, "ReferenceAnyValue"));

			return this;
		}
	}
}